#include "NeoSliderPrivate.h"
#include "NeoSlider.h"

NeoSliderPrivate::NeoSliderPrivate(QObject *parent)
    : QObject(parent),
      pIndicatorColor(Qt::white),
      pTrackColor(Qt::blue),
      pBackgroundColor(Qt::gray),
      pIndicatorRadius(0),
      pIndicatorStartPosition(0, 0)
{
}

NeoSliderPrivate::~NeoSliderPrivate() = default;

int NeoSliderPrivate::positionToValue(int position) const
{
    NEO_PRIVATE_POINT(const NeoSlider)
    return q->minimum() + (position * (q->maximum() - q->minimum())) / (q->width() - q->height());
}

int NeoSliderPrivate::valueToPosition(int value) const
{
    NEO_PRIVATE_POINT(const NeoSlider)
    return (value - q->minimum()) * (q->width() - q->height()) / (q->maximum() - q->minimum());
}

int NeoSliderPrivate::mousePositionForValue(QPointF pos) const
{
    return positionToValue(pos.x() - pIndicatorStartPosition.x());
}

void NeoSliderPrivate::updateWidgetGeometry(QSize size)
{
    pIndicatorRadius = size.height() / 2 - 2;
    pIndicatorStartPosition = QPointF(size.height() / 2, size.height() / 2);
}

void NeoSliderPrivate::drawBackground(QPainter *painter)
{
    NEO_PRIVATE_POINT(NeoSlider)
    painter->save();
    QRect rect = QRect(0, 0, q->width(), q->height()).adjusted(1, 1, -1, -1);
    qreal radius = q->orientation() == Qt::Horizontal ? rect.height() / 2.0 : rect.width() / 2.0;
    painter->setPen(pBackgroundColor);
    painter->setBrush(pBackgroundColor);
    painter->drawRoundedRect(rect, radius, radius);
    painter->restore();
}

void NeoSliderPrivate::drawTrack(QPainter *painter)
{
    NEO_PRIVATE_POINT(NeoSlider)
    painter->save();
    QRect trackRect = q->orientation() == Qt::Horizontal ? QRect(0, 0, q->height() + valueToPosition(q->sliderPosition()), q->height()).adjusted(NEO_RADIUS_ADJUSTED_VALUES)
                                                         : QRect(0, 0, q->width(), q->height() + valueToPosition(q->sliderPosition())).adjusted(NEO_RADIUS_ADJUSTED_VALUES);
    qreal radius = q->orientation() == Qt::Horizontal ? trackRect.height() / 2.0 : trackRect.width() / 2.0;
    painter->setPen(pTrackColor);
    painter->setBrush(pTrackColor);
    painter->drawRoundedRect(trackRect, radius, radius);
    painter->restore();
}

void NeoSliderPrivate::drawIndicator(QPainter *painter)
{
    NEO_PRIVATE_POINT(NeoSlider)
    painter->save();
    painter->setBrush(pIndicatorColor);
    QRect indicatorRect = q->orientation() == Qt::Horizontal
                              ? QRect(q->height() / 2 - pIndicatorRadius + valueToPosition(q->sliderPosition()), q->height() / 2 - pIndicatorRadius, 2 * pIndicatorRadius, 2 * pIndicatorRadius)
                              : QRect(q->width() / 2 - pIndicatorRadius, q->height() / 2 - pIndicatorRadius + valueToPosition(q->sliderPosition()), 2 * pIndicatorRadius, 2 * pIndicatorRadius);
    painter->drawEllipse(indicatorRect);
    painter->restore();
}